<?php
class ThirdOrder extends KF_Auth_Controller{
	/*
        订单列表
	*/
	public function index()
	{
        if(IS_POST){
            $where = array();
            if(empty($_GET['storeId']) == false){
            	$where[] = sprintf("YID = %s", $_GET['storeId']);
            }

            if(empty($_GET['platformId']) == false){
                $where[] = sprintf("PTID = %s", $_GET['platformId']);
            }

            if(empty($_GET['ZT']) == false){
                $where[] = sprintf("ZT = %s", $_GET['ZT']);
            }

            if(empty($_GET['start_date']) == false){
                $where[] = sprintf("createtime >= %d", strtotime(sprintf("%s 00:00:00",$_GET['start_date'])));
            }

            if(empty($_GET['end_date']) == false){
                $where[] = sprintf("createtime <= %d", strtotime(sprintf("%s 23:59:59",$_GET['end_date'])));
            }
            
            $config = array(
                'table' => 'kfsy_pingtai.kf_order_delivery',
                'columns' => array(
                    array('db' => 'ID'),
                    array('db' => 'DH'),
                    array('db' => 'PTID'),
                    array('db' => 'YID'),
                    array('db' => 'PSJL'),
                    array('db' => 'PSJG'),
                    array('db' => 'SFSJ'),
                    array('db' => 'JDSJ'),
                    array('db' => 'FPSJ'),
                    array('db' => 'ZT'),                    
                    array('db' => 'createtime'),
                    array('db' => 'updatetime')
                ),
                'where' => implode(' and ', $where),
                'order' => 'ID desc'
            );

            $this->load->library('dataTables', $config);
            $result = $this->datatables->search();

            $this->load->model("Common_model", "CommonModel");
            $CommonModel = $this->CommonModel;

            $allStoreName = $CommonModel->getAllStoreName();

            $allStore = array();
            foreach ($allStoreName as $key => $val) {
                $allStore[$val['ID']] = $val['Caption'];
            }

            if ($result['data'])
            {
                foreach ($result['data'] as $key => $value) {
                    $platform_info = $this->db->where('ID',$value['PTID'])->get('kfsy_pingtai.kf_delivery_platform')->row_array();
                    $result['data'][$key]['PTNAME'] = $platform_info['TL'];

                    $order_status = $CommonModel->getStatusNameById($value['ZT']);
                    $result['data'][$key]['storeName'] = $allStore[$value['YID']];

                    $result['data'][$key]['ZT'] = $order_status;
                    
                    $result['data'][$key]['createtime'] = date("Y-m-d H:i:s", $value['createtime']);
                    $result['data'][$key]['updatetime'] = date("Y-m-d H:i:s", $value['updatetime']);
                }
            }
            exit(json_encode($result));
        }

        $this->load->model('Store_model');
        $storeList = $this->Store_model->getStoreInfo('ID,Caption');//药店列表

        $this->load->model('Common_model');
        $orderStatusList = $this->Common_model->getStatusNameById();//订单状态列表

        $this->load->model('Platform_model');
        $platformList = $this->Platform_model->getPlatformInfo();//配送平台列表

        $this->load->view("third_order/index", array("storeList" => $storeList, "orderStatusList" => $orderStatusList, "platformList" => $platformList));
	}

    /*
        获取订单状态
    */
    public function orderStatus()
    {
        $id = $_GET['id'];

        $this->load->library('AdminApi/DeliveryInfo', '', 'DeliveryInfo');
        $DeliveryInfo = $this->DeliveryInfo;
        //获取订单信息
        $data = $DeliveryInfo->getDeliveryInfoById($id);

        //获取运单快递员信息
        $courierInfo = $DeliveryInfo->getDeliveryInfo($data['DH'],$data['PTID']);

        $this->load->model("Common_model", "CommonModel");
        $CommonModel = $this->CommonModel;

        $PlatformInfo = $CommonModel->getPlatformInfo($data['PTID']);

        $order_status = $CommonModel->getStatusNameById($data['ZT']);
        //获取订单日志
        
        $log = $DeliveryInfo->getDeliveryLogByDH($data['DH'], $data['PTID']);

        foreach ($log as $key => $val) {
            $log[$key]['ZT'] = $CommonModel->getStatusNameById($val['ZT']);

            if($key == 0)
            {
                $log[$key]['dif_time'] = '—';
                $log[$key]['all_time'] = '—';
            }else
            {
                $log[$key]['dif_time'] = $this->formatTime($val['createtime']-$log[$key-1]['createtime']);

                $log[$key]['all_time'] = $this->formatTime($val['createtime']-$log[0]['createtime']);
            } 
            $log[$key]['time'] = date("m-d H:i:s", $val['createtime']);
        }
       
        $result = array(
                'data'=>$data,
                'courierInfo'=>$courierInfo,
                'pt_name'=>$PlatformInfo,
                'order_status'=>$order_status,
                'log'=>$log
            );
        
        $this->load->view("third_order/order_status", $result);       
    }

    /*
      *    获取所有第三方平台配送费用
    */
    public function orderFee()
    {
        $order_id = $_GET['order_id'];

        $url = 'http://' . $_SERVER['SERVER_NAME'] . '/api/admin_api/OrderCommonModel.class.php?order_id='.$order_id;
        header("dd-batch-url:" . $url);

        $order_fee = file_get_contents($url);
        $order_fee = json_decode($order_fee,true);

        $result = array('order_fee' => $order_fee);

        $this->load->view("third_order/order_fee", $result);

    }

    /*
        获取订单商品详情
    */
    public function orderDetail()
    {
        $order_id = $_GET['order_id'];
        // $this->load->model("OrderMgr_model", "OrderMgrModel");
        // $OrderMgrModel = $this->OrderMgrModel;

        // $orderDetail = $OrderMgrModel
        //     ->getOrderDetail($order_id);

        // $data = array(
        //     "order_id" => $order_id,
        //     "order_detail" => $orderDetail
        // );
        $this->load->view("third_order/order_detail", $data);

    }

    /*
        获取订单详情
    */
    public function orderInfo()
    {
        $order_id = $_GET['order_id'];
        $this->load->model("OrderMgr_model", "OrderMgrModel");
        $OrderMgrModel = $this->OrderMgrModel;

        $orderInfo = $OrderMgrModel
            ->getOrderInfoById($order_id);

        $orderDetail = $OrderMgrModel
            ->getOrderDetailBySN($orderInfo['sn']);

        $orderInfo = $OrderMgrModel
            ->formatOrderInfo($orderInfo);


        $data = array(
            "order_id" => $order_id,
            "order_info" => $orderInfo,
            "order_detail" => $orderDetail
        );

        $this->load->view("order_mgr/order_info", $data);
    }

    public function formatTime($time = '')
    {

        $m = (int) ($time / 60);

        $s = $time % 60;

        $m = str_pad($m, 2, "0", STR_PAD_LEFT);
        $s = str_pad($s, 2, "0", STR_PAD_LEFT);

        $str = sprintf('%s" %s', $m, $s);
        return $str;
    }

    /**
    * 修改订单状态
    */
    public function updateOrderStatus()
    {
        $order_id = $_POST['order_id'];
        $order_id = implode(',', $order_id);

        $this->load->library('AdminApi/DeliveryInfo', '', 'DeliveryInfo');
        $DeliveryInfo = $this->DeliveryInfo;

        $data = $DeliveryInfo->getDeliveryLastStatus($order_id);

        $this->load->model('Common_model');
        foreach ($data as $key => $val) {
            $statusName = $this->Common_model->getStatusNameById($val['ZT']);
            $data[$key]['ZT'] = $statusName;
        }
        
        echo json_encode(array('code' => 0, 'msg' => '获取成功', 'data' => $data));
    }

    /**
    *   获取第三方配送员订单信息
    */
    public function getDeliveryDriverOrder()
    {
        $driver_name = $_GET['driver_name'];
        $search_date = $_GET['search_date'];
        $store_id = $_GET['store_id'];

        $this->load->library('AdminApi/DeliveryDriver', '', 'DeliveryDriver');
        $this->load->library('AdminApi/OrderCommonModel', '', 'OrderCommonModel');

        $DeliveryDriver = $this->DeliveryDriver;
        $OrderCommonModel = $this->OrderCommonModel;

        //获取第三方配送员订单
        $driverOrder = $DeliveryDriver->getOrderList($driver_name, $search_date, $store_id);
        $driverOrder = implode(',', $driverOrder);
        //通过订单号获取客户经纬度信息
        $customerLocation = $OrderCommonModel->getCustomerLocation($driverOrder);
        $customerLocation = array_values($customerLocation);
        //获取药店经纬度信息
        $storeLocation = $OrderCommonModel->getStoreLocation($store_id);

        $data = array('customerLocation'=>$customerLocation, 'storeLocation'=>$storeLocation);
        $this->load->view("third_order/delivery_driver", $data);

    }

    
    /**
    * phpexcel导出文件
    */
    
    public function exportExcel()
    {
        $_POST['length'] = "1000000000";
        $data = $this->getOrderData();
        $data = $data['data'];

        $fileData = array();

        foreach ($data as $key => $value) {
            $fileData[$key]['ID'] = $value['ID'];
            $fileData[$key]['DH'] = $value['DH'];
            $fileData[$key]['storeName'] = $value['storeName'];
            $fileData[$key]['PTNAME'] = $value['PTNAME'];
            $fileData[$key]['PSJL'] = $value['PSJL'];
            $fileData[$key]['PSJG'] = $value['PSJG'];
            $fileData[$key]['ZT'] = $value['ZT'];
            $fileData[$key]['createtime'] = $value['createtime'];
            $fileData[$key]['updatetime'] = $value['updatetime'];
        }

        $headArr = array(
            '#',
            '快方订单号',
            '药店名称',
            '配送平台',
            '配送距离 (m)',
            '配送费用 (￥)',
            '状态',
            '创建时间',
            '更新时间'
        );
        $fileName = 'order';
         
        //检查文件名  
        if (empty($fileName)) {  
            exit;  
        }  
  
        $date = date("Y_m_d", time());  
        $fileName .= "_{$date}.xls";  

  
        $this->load->library('PHPExcel');  
        $this->load->library('PHPExcel/IOFactory');  

  
        //创建PHPExcel对象  
        $objPHPExcel = new PHPExcel();  
  
        $objPHPExcel->getProperties();  
  
        //设置表头  
        $key = ord("A");  
        foreach ($headArr as $v) {  
            $colum = chr($key);  
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);  
            $key += 1;  
        }  
  
  
        $column = 2;  
        $objActSheet = $objPHPExcel->getActiveSheet();  
        foreach ($fileData as $key => $rows) { //行写入  
            $span = ord("A");  
            foreach ($rows as $keyName => $value) { // 列写入  
                $j = chr($span);  
                $objActSheet->setCellValue($j . $column, $value);  
                $span++;  
            }  
            $column++;  
        }  
  
        $fileName = iconv("utf-8", "gb2312", $fileName);  
        //重命名表  
  
        //设置活动单指数到第一个表,所以Excel打开这是第一个表  
        $objPHPExcel->setActiveSheetIndex(0);  
        ob_end_clean(); //清除缓冲区,避免乱码  
        header('Content-Type: application/vnd.ms-excel');  
        header("Content-Disposition: attachment;filename=\"$fileName\"");  
        header('Cache-Control: max-age=0');  
  
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5'); 
        $objWriter->save('php://output'); //文件通过浏览器下载  
        exit;  
    }

    /**
    *   获取订单数据
    */

    public function getOrderData()
    {
        $where = array();
        if(empty($_GET['storeId']) == false){
            $where[] = sprintf("YID = %s", $_GET['storeId']);
        }

        if(empty($_GET['platformId']) == false){
            $where[] = sprintf("PTID = %s", $_GET['platformId']);
        }

        if(empty($_GET['ZT']) == false){
            $where[] = sprintf("ZT = %s", $_GET['ZT']);
        }

        if(empty($_GET['start_date']) == false){
            $where[] = sprintf("createtime >= %d", strtotime($_GET['start_date']));
        }

        if(empty($_GET['end_date']) == false){
            $where[] = sprintf("createtime <= %d", strtotime($_GET['end_date']));
        }
        
        $config = array(
            'table' => 'kfsy_pingtai.kf_order_delivery',
            'columns' => array(
                array('db' => 'ID'),
                array('db' => 'DH'),
                array('db' => 'PTID'),
                array('db' => 'YID'),
                array('db' => 'PSJL'),
                array('db' => 'PSJG'),
                array('db' => 'SFSJ'),
                array('db' => 'JDSJ'),
                array('db' => 'FPSJ'),
                array('db' => 'ZT'),                    
                array('db' => 'createtime'),
                array('db' => 'updatetime')
            ),
            'where' => implode(' and ', $where),
            'order' => 'ID desc'
        );

        $this->load->library('dataTables', $config);
        $result = $this->datatables->search();

        $this->load->model("Common_model", "CommonModel");
        $CommonModel = $this->CommonModel;

        $allStoreName = $CommonModel->getAllStoreName();

        $allStore = array();
        foreach ($allStoreName as $key => $val) {
            $allStore[$val['ID']] = $val['Caption'];
        }
                
        if ($result['data'])
        {
            foreach ($result['data'] as $key => $value) {
                $platform_info = $this->db->where('ID',$value['PTID'])->get('kfsy_pingtai.kf_delivery_platform')->row_array();
                $result['data'][$key]['PTNAME'] = $platform_info['TL'];

                $order_status = $CommonModel->getStatusNameById($value['ZT']);
                $result['data'][$key]['storeName'] = $allStore[$value['YID']];

                $result['data'][$key]['ZT'] = $order_status;
                
                $result['data'][$key]['createtime'] = date("Y-m-d H:i:s", $value['createtime']);
                $result['data'][$key]['updatetime'] = date("Y-m-d H:i:s", $value['updatetime']);
            }
        }
        return $result;
    }
    
    public static function doGet($url, $param = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == 200) {
            return $result;
        }
        return false;
    }

    /*
        获取今日超距订单
    */
    public function todayFatalDeliery()
    {
        $url = sprintf("http://pt.kfyao.com/api/notify/Fn_2BXZB6J0.php?m=getFnLog&n=get_KM.%s.log", date("Y-m-d"));

        $content = $this->doGet($url);



        $conArr = array();
        preg_match_all("/.*\[* * \]*res/",  $content, $conArr);

        $res = array();

        foreach ($conArr[0] as $key => $value) {
            $tmpArr = explode(" params :", $value);
            $orderId = explode("?KFID=", $tmpArr[0]);
            $orderId = explode(" ]", $orderId[1]);
            $orderId = $orderId[0];

            $location = explode("res", $tmpArr[1]);
            $location = json_decode($location[0], true);

            $res[] = array(
                "order_id" => $orderId,
                "location" => $location
            );
        }

        $data = array(
            "order_list" => $res
        );
        $this->load->view("third_order/km_list", $data);
    }

    /*
        高德步行导航
    */
    public function Walking()
    {
        $data = array();
        
        $this->load->view("third_order/walking", $data);
    }
}